import face_recognition
import numpy as np
import cv2
import json
from chinese import chinese

def get_feature(img):
    img_RGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    encoding=None
    face_locations=face_recognition.face_locations(img_RGB)
    for botton,right,top,left in face_locations:
        img = cv2.rectangle(img, (left, top), (right, botton), (0, 0, 255))
    encodings=face_recognition.face_encodings(img_RGB,face_locations)
    if len(encodings)>0:
        encoding=encodings[0]
    return encoding

class Face_recognition:
    def __init__(self,path):
        self.path=path
        try:
            with open(path,'r') as f:
                json_dict:dict=json.loads(f.read())
            self.names=list(json_dict.keys())
            self.encodings=[np.array(list_enc) for list_enc in json_dict.values()]
        except:
            self.names=[]
            self.encodings=[]
    
    def face_reading(self,img):
        encoding=get_feature(img)
        if encoding is not None:
            distances=face_recognition.face_distance(self.encodings,encoding)
        #print(distances)
            if distances.min() > 0.3:
                return None
            min_dis=distances.argmin()
            return [self.names[min_dis],distances]
        return None

#写数据
    def __data_write(self):
        encoding_list=[enc.tolist() for enc in self.encodings]
        dic=dict(zip(self.names,encoding_list))
        with open(self.path, 'w') as file:
            json.dump(dic, file)

#增加脸
    def face_intering(self,img,name,encoding):
        #encoding,_=get_feature(img)
        self.names.append(name)
        self.encodings.append(encoding)
        self.__data_write()

#删除脸
    def face_pop(self,name:str):
        index=self.names.index(name)
        self.names.pop(index)
        self.encodings.pop(index)
        self.__data_write()

if __name__=='__main__':
    path='face_data.json'
    face=Face_recognition(path)
    cap=cv2.VideoCapture(0)
    while cap.isOpened():
        ret,img2=cap.read()
        infor=face.face_reading(img2)
        if infor is not None:
            print(infor[0])
        cv2.imshow('aw',img2)
        cv2.waitKey(1)

